package com.xzj.admin.analysis.base.common.handle;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xzj.admin.analysis.base.domain.ResMessageManage;
import com.xzj.admin.analysis.base.domain.CommonFlowInfo;
import com.xzj.admin.analysis.base.function.JudgeSubFun;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: xzj-admin
 * @ClassName: CommonAbstractAnalysisHandle
 * @description: 公共抽象方法层
 * @author: XiaZunJun
 * @create: 2024-11-11 16:00
 */
@Getter
@Slf4j
public abstract class CommonAbstractAnalysisHandle implements ICommonAnalysisHandle{

    private final String cloudId;

    private final String cloudType;

    private final ThemeSpecialAnalysisHandle themeSpecialAnalysisHandle;

    public CommonAbstractAnalysisHandle(String cloudId,String cloudType) {
        this.cloudType = cloudType;
        this.cloudId = cloudId;
        this.themeSpecialAnalysisHandle = null;
    }

    public CommonAbstractAnalysisHandle(String cloudId,String cloudType,ThemeSpecialAnalysisHandle themeSpecialAnalysisHandle) {
        this.cloudType = cloudType;
        this.cloudId = cloudId;
        this.themeSpecialAnalysisHandle = themeSpecialAnalysisHandle;
    }

    @Override
    public void analysisBefore(JSONObject msgJson) {}

    @Override
    public void analysisSubResource(String theme,JSONObject row, String parentId, String fieldName,
                                    JSONArray subThemeRows) {
        try {
            if (isJudgeSubFun(theme)) {
                JudgeSubFun judgeSubFun = getJudgeSubFun(theme);
                judgeSubFun.accept(row, parentId, fieldName, subThemeRows);
            }
        } catch (Exception e) {
            log.error("解析字子资源报错-{}", theme);
        }
    }

    private static final Map<String, JudgeSubFun> JUDGE_SUB_FUN_MAP = new ConcurrentHashMap<>();

    protected static void registerJudgeSubFun(String theme, JudgeSubFun judgeSubFun) {
        JUDGE_SUB_FUN_MAP.put(theme, judgeSubFun);
    }

    protected static JudgeSubFun getJudgeSubFun(String theme) {
        return JUDGE_SUB_FUN_MAP.get(theme);
    }

    protected static boolean isJudgeSubFun(String theme) {
        return JUDGE_SUB_FUN_MAP.containsKey(theme);
    }

    public void analysisSpecial(ResMessageManage message, CommonFlowInfo info){
        if(null != themeSpecialAnalysisHandle){
            themeSpecialAnalysisHandle.handle(message,info);
        }
    }
}
